package com.newflypig.jblog.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.newflypig.jblog.dao.IBaseDAO;
import com.newflypig.jblog.dao.ISystemDAO;
import com.newflypig.jblog.model.BlogSystem;
import com.newflypig.jblog.service.ISystemService;

@Service("systemService")
public class SystemServiceImpl extends BaseServiceImpl<BlogSystem> implements ISystemService{

	@Resource(name = "systemDao")
	private ISystemDAO systemDao;
	
	@Override
	protected IBaseDAO<BlogSystem> getDao() {
		return this.systemDao;
	}

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public boolean checkLogin(String username, String password) {
		return this.systemDao.checkLogin(username, password);
	}

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public String getValue(String key) {
		return this.systemDao.getValue(key);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void update(String key, String value) {
		this.systemDao.update(key, value);		
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public int updatePwd(String oldPwd, String newPwd) {
		return this.systemDao.updatePwd(oldPwd, newPwd);
	}

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public boolean checkGuest(String username, String password) {
		List<BlogSystem> list = this.systemDao.findByDC(
			DetachedCriteria
				.forClass(BlogSystem.class,"system")
				.add(Restrictions.or(
					Restrictions.and(
						Restrictions.eq("key", BlogSystem.KEY_GUEST_USERNAME)
						,Restrictions.eq("value", username)
					)
					,Restrictions.and(
						Restrictions.eq("key", BlogSystem.KEY_GUEST_PASSWORD)
						,Restrictions.eq("value", password)
					)
				))
		);
		
		return list != null && list.size() == 2;
	}

}
